package org.demo.spring.data.springaction;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * JdbcTemplate模版 spring 提供的基于JDBC的模版
 */
public class JdbcTemplateTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext-jdbc-spring-jdbcTemplate-test.xml");
        JdbcTemplate jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
        String sql = "SELECT * FROM user WHERE id = ?";
        PreparedStatementSetter preparedStatementSetter = new PreparedStatementSetter() {
            public void setValues(PreparedStatement preparedStatement) throws SQLException {
                preparedStatement.setInt(1,1);
            }
        };
        ResultSetExtractor resultSetExtractor = new ResultSetExtractor() {
            public Object extractData(ResultSet resultSet) throws SQLException, DataAccessException {
                if(resultSet.next()){
                    int id = resultSet.getInt("id");
                    String name = resultSet.getString("name");
                    User user = new User();
                    user.setId(id);
                    user.setName(name);
                    return user;
                }
                return null;
            }
        };
        User user = (User) jdbcTemplate.query(sql, preparedStatementSetter, resultSetExtractor);
        User user1 = jdbcTemplate.queryForObject(sql, new RowMapper<User>() {
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                    System.out.println(i);
                    int id = resultSet.getInt("id");
                    String name = resultSet.getString("name");
                    User user = new User();
                    user.setId(id);
                    user.setName(name);
                    return user;
            }
        },2);
        System.out.println(user);
        System.out.println(user1);
    }
}
